// packageK/application/application.js
const app = getApp()
import WxValidate from "../lib/WxValidate"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 申请类型：1-供应商, 2-商户, 3-招商员
    type: 1,
    typeObj: { 
      1: { title: '供应商', route: 'platformApplet.supplier.index' },
      2: { title: '商户', route: 'platformApplet.business.index' },
      3: { title: '招商员', route: 'platformApplet.merchants.index' }
    },
    formData: {
      // account: '',
      // password: '',
      platform_name: '',
      logo: [],
      nickname: '',
      mobile: '',
      career_type: '',
      address: '',
      province_id: '',
      city_id: '',
      district_id: '',
      street: '',
      street_id: '',
      absolute_address: '',
      business_license: [],
      legal_person_front: [],
      legal_person_back: [],
      remark: '',
      agree: false,
      mc_merchants_id: ''
    },
    // 订阅审核消息模板id
    tmplIds: ['iRS4D4LGiLwAptNkJgvDDEI4KpFfL1-KBzP1hRXZuzQ'],
    uploaderUrl: "upload.uploadPic",
    protocolShow: false,
    verified: 0,
    areaList: {},
    areaValue: '110101',
    addressPopup: false,
    streetList: [],
    streetPopup: false,
  },

  /**
   * 输入框输入内容，数据双向绑定
   * @param {Object} e 
   */
  inputChange: function(e) {
    const value = e.detail
    const { name } = e.currentTarget.dataset
    let { formData } = this.data
    formData[name] = value
    this.setData({ formData })
  },

  /**
   * 招商员申请-职业类型选中
   * @param {Object} e 
   */
  careerChange: function(e) {
    const { detail } = e
    this.setData({ 'formData.career_type': detail})
  },

  /**
   * 初始化地区数据
   */
  initAreaData: function() {
    // 非商户申请没有地址
    if (this.data.type != 2) {
      return
    }
    const url = app.getNetAddresss('member.member-address.address')
    const _this = this
    wx.showLoading({
      title: '获取地址信息...',
    })
    app._postNetWork({
      url,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const { province, city, district} = resData.data
          let province_list = {}
          let city_list = {}
          let county_list = {}
          province.forEach(item => {
            province_list[item.id] = item.areaname
          })
          city.forEach(item => {
            city_list[item.id] = item.areaname
          })
          district.forEach(item => {
            county_list[item.id] = item.areaname
          })
          _this.setData({
            'areaList.province_list': province_list,
            'areaList.city_list': city_list,
            'areaList.county_list': county_list
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: resData.msg,
          })
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 显示/关闭popup
   * @param {Object} e 
   */
  triggerPopup(e) {
    const { item, isshow } = e.currentTarget.dataset
    if (item == 'streetPopup' && !this.data.formData.address) {
      wx.showToast({ title: '请先选择地址', icon: 'none' })
      return
    }
    this.setData({
      [item]: isshow,
    })
  },

  /**
   * 地区选中确认
   * @param {Object} e 
   */
  areaConfirm(e) {
    const { values } = e.detail;
    const fieldValue = values
        .map((option) => option.name)
        .join('/');
    this.setData({
      'formData.address': fieldValue,
      areaValue: values[2].code,
      'formData.street': '',
      addressPopup: false,
      'formData.province_id': values[0].code,
      'formData.city_id': values[1].code,
      'formData.district_id': values[2].code
    })
    this.getStreetData(values[2].code)
  },

  /**
   * 获取街道列表数据
   * @param {String|Number} code 
   */
  getStreetData: function(code = '') {
    if (!code) {
      wx.showToast({ icon: 'none', title: '缺少参数', })
      return
    }
    wx.showLoading({ title: '加载中' })
    const _this = this
    let urlStr = app.getNetAddresss("platformApplet.address.getAddress");
    urlStr += "&parentid=" + code + "&level_type=street"
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ streetList: resData.data })
        } else {
          wx.showToast({ title: resData.msg })
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 街道选中
   * @param {Object} e 
   */
  streetConfirm: function(e) {
    const { street = '', code = '' } = e.currentTarget.dataset
    this.setData({ 
      'formData.street': street, 
      'formData.street_id': code,
      streetPopup: false
    })
  },

  /**
   * 图片选中上传(多图)
   * @param {Object} e 
   */
  afterRead: function(e) {
    const { file = [] } = e.detail
    let promiseArray = []
    const uploaderUrl = app.getNetAddresss(this.data.uploaderUrl)
    wx.showLoading({
      title: '上传中',
    })
    file.forEach(item => {
      promiseArray.push(new Promise((resolve, reject) => {
        wx.uploadFile({
          filePath: item.url,
          name: 'file',
          url: uploaderUrl,
          success: function(res) {
            resolve(res)
          },
          fail: function(err) {
            reject(err)
          }
        })
      }))
    })
    Promise.all(promiseArray).then(resArray => {
      wx.hideLoading()
      const addUrlArray = resArray.map(item => {
        const resData = JSON.parse(item.data)
        return {url: resData.data.img_url}
      })
      const { formData } = this.data
      const { field } = e.currentTarget.dataset
      const currentImgUrls = [...this.data.formData[field], ...addUrlArray]
      formData[field] = currentImgUrls
      this.setData({ formData })
    }).catch(err => {
      wx.hideLoading()
    })
  },

  showProtocol: function() {
    // this.setData({ protocolShow: true })
    // wx.downloadFile({ //将文档下载到本地
    //   url: 'http://play.li-stack.top:88/pdf/sjisr-3-2-36-42.pdf',//pdf链接
    //   success(res) {
    //     wx.openDocument({ //打开文档
    //       filePath: res.tempFilePath,//本地文档路径
    //       fileType: "pdf",//文档类型
    //       showMenu: true,
    //       success: function (res) {
    //         wx.showToast({
    //           title: '打开文档成功',
    //         })
    //       },
    //       fail: function (res) {
    //         wx.showToast({
    //           title: '打开文档失败',
    //         })
    //       },
    //     })
    //   },
    // })
  },

  /**
   * 勾选协议状态改变
   * @param {Object} e 
   */
  agreeChange: function(e) {
    const { formData } = this.data
    formData.agree = e.detail
    this.setData({ formData })
  },

  /**
   * 提交申请
   */
  submitApplication: function(e) {
    const { formData, type, typeObj } = this.data
    const valid = this.WxValidate.checkForm(formData)
    // 验证通过
    if (valid) {
      if (!formData.agree) {
        app.tips(`请阅读并同意《${this.data.typeObj[this.data.type].title}协议》`)
        return
      }
      const { nickname, mobile, career_type, remark } = formData
      let data = {
        nickname,
        mobile,
        remark
      }
      // 招商员-职业类型
      if (type == 3) {
        data.career_type = career_type
      }
      // 商户
      if (type == 2) {
        const {
          platform_name,
          logo,
          address,
          province_id,
          city_id,
          district_id,
          street,
          street_id,
          absolute_address,
          business_license,
          legal_person_front,
          legal_person_back,
          mc_merchants_id
        } = formData
        data = Object.assign({}, data, {
          platform_name,
          logo: logo[0].url,
          address,
          province_id,
          city_id,
          district_id,
          street,
          street_id,
          absolute_address,
          business_license: business_license[0].url,
          legal_person_front: legal_person_front[0].url,
          legal_person_back: legal_person_back[0].url,
          mc_merchants_id
        })
      }
      const url = app.getNetAddresss(typeObj[type].route)
      const _this = this
      wx.showLoading({
        title: '加载中...',
      })
      app._postNetWork({
        url,
        data,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            wx.requestSubscribeMessage({
              tmplIds: _this.data.tmplIds,
              complete: function() {
                wx.showModal({
                  title: '成功',
                  content: '申请成功，等待审核',
                  showCancel: false,
                  confirmText: "确定",
                  complete: (res) => {
                    if (res.confirm) {
                      wx.navigateBack({
                        delta: -1
                      })
                    }
                  }
                })
              }
            })
          } else {
            app.tips(resData.msg)
          }
        },
        complete: function() {
          wx.hideLoading()
        }
      })
    } else {
      app.tips(this.WxValidate.errorList[0].msg)
    }
  },

  /**
   * 初始化表单验证规则
   */
  initValidata: function() {
    const rules = {
      // account: { required: true },
      // password: { required: true },
      nickname: { required: true },
      mobile: { required: true, tel: true }
    }
    const messages = {
      // account: { required: '请设置账号' },
      // password: { required: '请设置密码' },
      nickname: { required: '请填写真实姓名' },
      mobile: { required: '请填写手机号', tel: '请输入正确的手机号码' }
    }
    // 商户申请字段验证
    if (this.data.type == 2) {
      rules.platform_name = { required: true }
      rules.address = { required: true }
      rules.street = { required: true }
      rules.absolute_address = { required: true }
      rules.logo = { arrayNonAmpty: true }
      rules.business_license = { arrayNonAmpty: true }
      rules.legal_person_front = { arrayNonAmpty: true }
      rules.legal_person_back = { arrayNonAmpty: true }
      messages.platform_name = { required: '请设置商户名称' }
      messages.address = { required: '请选择地址' }
      messages.street = { required: '请选择街道' }
      messages.absolute_address = { required: '请填写详细地址' }
      messages.logo = { arrayNonAmpty: '请上传商户logo' }
      messages.business_license = { arrayNonAmpty: '请上传营业执照照片' }
      messages.legal_person_front = { arrayNonAmpty: '法人身份证正面照片' }
      messages.legal_person_back = { arrayNonAmpty: '法人身份证反面照片' }
    }
    // 招商员申请字段验证
    if (this.data.type == 3) {
      rules.career_type = { required: true },
      messages.career_type = { required: '请选择职业类型' }
    }
    this.WxValidate = new WxValidate(rules, messages)
    const _this = this
    // 验证数组是否为空
    this.WxValidate.addMethod('arrayNonAmpty', (value, param) => {
      return value && value.length > 0
    })
  },

  /**
   * 验证是否可申请
   */
  validateAppStatus: function() {
    wx.showLoading({
      title: '数据加载中...',
    })
    const _this = this
    const url = app.getNetAddresss('platformApplet.business.getApplyResult')
    app._getNetWork({
      url,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({
            verified: 1
          })
        } else {
          if(resData.msg === '已绑定供货商' && _this.data.type == 1){
            wx.redirectTo({
              url: '/packageK/my/my',
            })
            return false
          }

          if(resData.msg === '已绑定商户' && _this.data.type == 2){
            wx.redirectTo({
              url: '/packageK/my/my',
            })
            return false
          }

          if(resData.msg === '已绑定招商员' && _this.data.type == 3){
            wx.redirectTo({
              url: '/packageK/my/my',
            })
            return false
          }
          wx.showModal({
            title: '提示',
            content: resData.msg,
            confirmColor: '#DA3231',
            confirmText: '返回',
            showCancel: false,
            complete: (res) => {
              if (res.confirm) {
                wx.navigateBack({
                  delta: -1
                })
              }
            }
          })
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 扫招商员二维码进入的申请页面
    if (options.scene) {
      try {
        const sceneStr = decodeURIComponent(options.scene)
        const paramStr = sceneStr.split(',')[1]
        const paramArr = paramStr.split('&')
        let obj = {}
        for (let i = 0; i < paramArr.length; i++) {
          const str = paramArr[i].split('=')
          obj[str[0]] = str[1]
        }
        this.setData({
          type: obj.appType,
          'formData.mc_merchants_id': obj.merchants_id
        })
      } catch (err) {
        console.error(err)
      }
    }
    if (options.appType) {
      this.setData({ type: options.appType})
    }
    // 验证是否可申请
    this.validateAppStatus()
    // 初始化地址数据
    this.initAreaData()
    // 设置页面名称
    const { type, typeObj } = this.data
    wx.setNavigationBarTitle({
      title:  `${typeObj[type].title}申请`,
    })
    this.initValidata()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})